from django.db import models


class Product(models.Model):
    """
    商品模型，用于表示商品的基本信息，包括秒杀相关字段。
    """
    product_id = models.CharField(max_length=100, unique=True, verbose_name="商品ID")
    name = models.CharField(max_length=255, verbose_name="商品名称")
    description = models.TextField(blank=True, null=True, verbose_name="商品描述")
    stock = models.PositiveIntegerField(default=0, verbose_name="商品库存")
    price = models.DecimalField(max_digits=10, decimal_places=2, default=0.00, verbose_name="商品价格")

    # 秒杀相关字段
    flash_sale_price = models.DecimalField(max_digits=10, decimal_places=2, default=0.00, verbose_name="秒杀价格", blank=True, null=True)
    flash_sale_stock = models.PositiveIntegerField(default=0, verbose_name="秒杀库存", blank=True, null=True)
    flash_sale_start_time = models.DateTimeField(verbose_name="秒杀开始时间", blank=True, null=True)
    flash_sale_end_time = models.DateTimeField(verbose_name="秒杀结束时间", blank=True, null=True)

    # 时间戳，记录创建和更新的时间
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="更新时间")

    def __str__(self):
        return self.name

    def is_flash_sale_active(self):
        """
        判断当前商品是否处于秒杀时间内
        """
        from django.utils import timezone
        current_time = timezone.now()
        return self.flash_sale_start_time <= current_time <= self.flash_sale_end_time

    class Meta:
        verbose_name = "商品"
        verbose_name_plural = "商品"
        ordering = ['created_at']

        # 为商品名称、秒杀相关字段添加索引
        indexes = [
            models.Index(fields=['name']),  # 为商品名称添加索引，优化搜索
            models.Index(fields=['flash_sale_start_time', 'flash_sale_end_time']),  # 为秒杀时间范围添加复合索引
            models.Index(fields=['flash_sale_price']),  # 为秒杀价格添加索引
            models.Index(fields=['flash_sale_stock']),  # 为秒杀库存添加索引
        ]